home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
Windows News 2010 Summer - Disc 1
/
WN_Ete2010_CD1.iso
/
Onglet5
/
Weezo
/
Weezo setup.exe
/
{code_appDir}
/
www
/
includes
/
mySQLFunctions.php
< prev
next >
Wrap
PHP Script
|
2010-05-19
|
10KB
|
317 lines
<?php
/**
* MySQL database creation / connection
*
* PHP version 5
*
* LICENSE: This source file is subject to version 3.0 of the PHP license
* that is available through the world-wide-web at the following URI:
* http://www.php.net/license/3_0.txt. If you did not receive a copy of
* the PHP License and are unable to obtain it through the web, please
* send a note to license@php.net so we can mail you a copy immediately.
*
* @category NA
* @package NA
* @author Nicolas Bruley / Peer 2 World <contact@weezo.net>
* @copyright 2005-2009 Nicolas Bruley / Peer 2 World
* @license http://www.php.net/license/3_0.txt PHP License 3.0
* @version CVS: $Id:$
* @link http://www.weezo.net
* @since File available since Release 1.0.1
*/
/**
* @desc Initialize MySQL database for a Weezo resource
* If needed, Generate database, generate, set and save root password
* @param string $databaseName: name of database to create. Resource ID will be automatically appened
*
* @return mixed: result, true if database was created and all is OK, database name if database newly created, false if error
*/
function mySQLInit($databaseName){
// Add resource id to database name (except for root)
$databaseName=mySQLDatabase($databaseName);
// Check MySQL existence and databasename
if($databaseName=='root' || !file_exists(cfAppDataRootDir().'/MySQL/bin/mysqld.exe') || !mySQLValidName($databaseName)) return false;
// If passwords file doesn't exist, init database
if(!file_exists(cfAppDataRootDir().'/MySQL/MySQL.ini')){if(!mySQLInitRoot()) return false;}
// Load stored password
$passwords=parse_ini_file(cfAppDataRootDir().'/MySQL/MySQL.ini');
// If password set, db (should be) OK
if(isset($passwords[$databaseName])) {
$checked=cfMGetVar('weezoMySQLDatabasesChecked');
if(isset($checked[$databaseName])) return true;
// Check that database exists
mySQLConnectDB('root');
$result=mysql_query('SHOW DATABASES');
while ($row = mysql_fetch_assoc($result)) {
if(@$row['Database']==$databaseName) {
// Set as checked (cache result)
$checked[$databaseName]=1;
cfMSetVar('weezoMySQLDatabasesChecked',$checked);
return true;
}
}
}
// Generate password
$password=cfGenerateID(16);
$passwords[$databaseName]=$password;
// Connect as root user
mySQLConnectDB('root');
// Create database and user
mysql_select_db('mysql');
mysql_query("CREATE DATABASE IF NOT EXISTS ".$databaseName." ;");
mysql_query("CREATE USER ".$databaseName."@localhost IDENTIFIED BY '".$password."';");
mysql_query("GRANT USAGE ON * . * TO ".$databaseName."@localhost IDENTIFIED BY '".$password."' WITH MAX_QUERIES_PER_HOUR 0 MAX_CONNECTIONS_PER_HOUR 0 MAX_UPDATES_PER_HOUR 0 MAX_USER_CONNECTIONS 0 ;");
mysql_query("GRANT ALL PRIVILEGES ON ".$databaseName.".* TO ".$databaseName."@localhost WITH GRANT OPTION");
mysql_query('FLUSH PRIVILEGES');
mysql_close();
// Save password to file
mySQLWritePasswords($passwords);
return $databaseName;
}
/**
* @desc Display MySQL table
*
* @param string $table: table name
*/
function mySQLDisplayTable($table){
if(is_array($table)){
$result=$table;
}
else{
$query='SELECT * FROM '.$table;
$result=mysql_query($query);
echo "<b>".$table.'</b><br>';
}
if(!$result || mysql_num_rows($result)==0) echo 'Table vide<br/><br/>';
else{
echo '<table style="border:1px solid black; color:#550; font-family:arial; font-size:10px" cellspacing=0 cellpadding=0><tr>';
$rowNb=0;
echo '</tr>';
while ($row = mysql_fetch_assoc($result)) {
echo '<tr>';
if($rowNb==0) {
foreach ($row as $key=>$value) echo '<td style="font-weight:bold; padding:3px; background:#550; color:white; font-weight:bold; font-family:arial; font-size:10px">'.$key.'</td>';
echo '</tr>';
}
foreach ($row as $k2=>$v2) {
echo '<td style="border:1px dashed #AAA; padding:3px">';
if($k2=='ts') echo date('d/m/y h:i:s',$v2); else echo $v2;
echo '</td>';
}
echo "</tr>\n";
$rowNb++;
}
echo "</table>\n";
}
}
/**
* @desc Destroy a MySQL database and user
*
* @param string $resId : unique resource id
* @return boolean result
*/
function mySQLDestroyResource($resId){
mySQLConnectDB('root');
mysql_select_db('mysql');
$dbIds=explode("\n",@file_get_contents(cfAppDataRootDir().'/MySQL/MySQL.ini'));
foreach ($dbIds as $nb=>$line) if(strpos($line,$resId)){
unset($dbIds[$nb]);
$dbId=substr($line,0,strpos($line,'='));
// Destroy user
mysql_query("DROP USER '".$dbId."'@'localhost'");
// Destroy database
mysql_query("DROP DATABASE IF EXISTS `".$dbId."`");
// Clean passwords file
file_put_contents(cfAppDataRootDir().'/MySQL/MySQL.ini',join("\n",$dbIds));
mysql_close();
return true;
}
mysql_close();
return false;
}
/**
* @desc return resource unique Id : if resource env is set, return cfRGetVar('id'),
* else parse resource config data and return id entry
*
* @return string : resource unique Id
*/
function mySQLUniqueResourceId(){
// Return resource ID
if(isset($_SESSION['activeResourceId'])) return cfRGetVar('id');
// for extensions that use their own session, use stored weezo session to retreive id
elseif(isset($_ENV['weezoSession']['res'][$_ENV['weezoSession']['activeResourceId']]['id'])) return $_ENV['weezoSession']['res'][$_ENV['weezoSession']['activeResourceId']]['id'];
elseif(cfGGetVar('configResourceUniqueId')) return cfGGetVar('configResourceUniqueId');
elseif(@$_ENV['resourceConfigFilename'] || cfGGetVar('resourceConfigFilename')){
$resourceConfigFilename=((isset($_ENV['resourceConfigFilename']))?$_ENV['resourceConfigFilename']:cfGGetVar('resourceConfigFilename'));
if(!($resData=cfParse_ini_file(cfAppDataDir().'/'.$resourceConfigFilename))) return false;
if(!isset($resData['id'])) return false;
else {
cfGSetVar('configResourceUniqueId',$resData['id']);
return $resData['id'];
}
}
else return false;
}
/**
* @desc Called on MySQL server connection error
* Display error page
*
*/
function connectionError($err=false){
global $w_lng;
require_once(INCLUDE_DIR.'outputFunctions.php');
outDisplayErrorPage('MySQL connection error: '.$err,false,true);
}
/**
* @desc write mysql users/passwords in mysql/mysql.ini file
*
* @param array $passwords
* @return boolean result
*/
function mySQLWritePasswords($passwords){
if (!$fp = fopen(cfAppDataRootDir().'/MySQL/MySQL.ini', 'w')) return false;
foreach ($passwords as $key=>$value) fwrite($fp,$key.'='.$value."\n");
fclose($fp);
}
function mySQLValidName($name){
return true;
}
/**
* @desc Initialize MySQL for Weezo
* Generate, set and save root password
* @param boolean $changePassword : set to true to renew with randmo password or to new password value
*
* @return boolean : result : true if MySQL present and correctly configured
*/
function mySQLInitRoot($changePassword=false){
// Check MySQL existence
if(!file_exists(cfAppDataRootDir().'/MySQL/bin/mysqld.exe')) return false;
// Load stored password
if(file_exists(cfAppDataRootDir().'/MySQL/MySQL.ini')) $passwords=parse_ini_file(cfAppDataRootDir().'/MySQL/MySQL.ini');
else $passwords=false;
// Check stored password
if(isset($passwords['root']) && strlen($passwords['root'])){
if(!$socket=@fsockopen('127.0.0.1',mySQLPort(),$errno, $errstr, 3)) connectionError('connection failed (1)'); else fclose($socket);
if(mysql_connect('localhost','root',$passwords['root'])){
mysql_close();
if(!$changePassword) return true;
$password=$passwords['root'];
}
else $password='';
}
else $password='';
// Try to connect to MySQL server with blank password
if(!$socket=@fsockopen('127.0.0.1',mySQLPort(),$errno, $errstr, 3)) connectionError('connection failed (2)'); else fclose($socket);
if(!mysql_connect('localhost','root',$password)) return false;
// Connect mysql database
if(!mysql_select_db('mysql')) return false;
// Set new password
if(!$password || $changePassword===true) $password=md5(rand(0,9999999999).microtime(true)); else $password=$changePassword;
// Save and set password
$passwords['root']=$password;
if(mysql_query('SET PASSWORD FOR root@localhost=PASSWORD("'.$password.'")')){
mySQLWritePasswords($passwords);
mysql_query('FLUSH PRIVILEGES');
}
mysql_query("DROP USER ``@`%`");
mysql_close();
return true;
}
/**
* @desc return host for MySQL connection
*
* @return string : host name
*/
function mySQLHost($database=false){
return 'localhost';
}
/**
* @desc return port for MySQL database
*
* @return string : port number
*/
function mySQLPort($database=false){return '3306';}
/**
* @desc return user name for MySQL database
*
* @return string : user name
*/
function mySQLUser($database){
if($database=='root') return $database;
// Get resource unique Id
if(!($ruid=mySQLUniqueResourceId())) return false;
return strtolower(substr($database.$ruid,0,16));
}
/**
* @desc return database name for MySQL connection
*
* @return string : user name
*/
function mySQLDatabase($database){return mySQLUser($database);}
/**
* @desc return user password for MySQL connection
*
* @return string : password
*/
function mySQLPassword($database){
if(!$database) return false;
if(!file_exists(cfAppDataRootDir().'/MySQL/MySQL.ini')) {
require_once(INCLUDE_DIR.'outputFunctions.php');
outDisplayErrorPage(cfCaption('extMySQLRequired'));
}
$passwords=parse_ini_file(cfAppDataRootDir().'/MySQL/MySQL.ini');
if(isset($passwords[mySQLDatabase($database)])) return $passwords[mySQLDatabase($database)];
return false;
}
/**
* @desc Connect and select a database
*
* @return boolean
*/
function mySQLConnectDB($database){
if(!$socket=@fsockopen('127.0.0.1',mySQLPort(),$errno, $errstr, 3)) connectionError('connection failed (3)'); else fclose($socket);
if(!mysql_connect($host=mySQLHost($database),$user=mySQLUser($database),mySQLPassword($database))) return false;
if($database=='root') return true;
if(!mysql_select_db(mySQLDatabase($database))){
mysql_close();
return false;
}
return true;
}
?>